package cn.yza.并发.锁.原子自增;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Honglixi
 * @create 2021-11-15 16:11
 */
public class AtomicTest {
    public static AtomicInteger race = new AtomicInteger(0);

    public static void increase() {
        race.incrementAndGet();
    }
    private static final int THREADS_COUNT = 20;

    public static void main(String[] args) {
        Thread[] threads = new Thread[THREADS_COUNT];
        for (int i = 0; i < THREADS_COUNT; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    increase();
                }
            });
            threads[i].start();
        }
        //保证20个线程全都自增完
        while (Thread.activeCount() > 1) {
            Thread.yield();
            System.out.println(race);
        }
    }
}
